import md5 from 'js-md5';
import { useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { doLogApi } from 'api/user';
import { HOME_URL } from '@conf';
import { connect } from 'react-redux';
import { setToken, setUserInfo, setAuthLevel } from '@redux/global/action';
import { useTranslation } from 'react-i18next';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

const mapDispatchToProps = { setToken, setUserInfo, setAuthLevel };
export default connect(
	null,
	mapDispatchToProps
)(({ setToken, setUserInfo, setAuthLevel }: any) => {
	const { t } = useTranslation();
	const navigate = useNavigate();
	const [form] = Form.useForm();
	const [loading, setLoading] = useState<boolean>(false);
	// 登录
	const onFinish = async (loginForm: any) => {
		try {
			setLoading(true);
			loginForm.password = md5(loginForm.password);
			const { token, level, ...userInfo }: any = await doLogApi(loginForm);
			setToken(token);
			setUserInfo(userInfo);
			setAuthLevel(level);
			message.success('登录成功！');
			navigate(HOME_URL);
		} finally {
			setLoading(false);
		}
	};
	return (
		<Form
			form={form}
			name='basic'
			labelCol={{ span: 5 }}
			initialValues={{ remember: true }}
			onFinish={onFinish}
			size='large'
			autoComplete='off'>
			<Form.Item name='account' rules={[{ required: true, message: '请输入用户名' }]}>
				<Input placeholder='账号/用户名' prefix={<UserOutlined />} />
			</Form.Item>
			<Form.Item name='password' rules={[{ required: true, message: '请输入密码' }]}>
				<Input.Password autoComplete='new-password' placeholder='密码' prefix={<LockOutlined />} />
			</Form.Item>
			<Form.Item>
				<Button type='primary' htmlType='submit' loading={loading} icon={<UserOutlined />}>
					{t('login.confirm')}
				</Button>
			</Form.Item>
			{process.env.NODE_ENV !== 'production' && (
				<Form.Item>
					{Object.entries({
						super: ['keke', '123123'],
						admin: ['pakchoi', '123123'],
						// users: ['keke1233', 'keke1233'],
					}).map(([key, value]) => (
						<Button
							type='link'
							key={key}
							onClick={() => {
								form.setFieldsValue({
									account: value[0],
									password: value[1],
								});
							}}>
							测试-{key}
						</Button>
					))}
				</Form.Item>
			)}
		</Form>
	);
});
